#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <LibLOL.c>
#include <ogcsys.h>
#include <malloc.h>
#include <ctype.h>
#include <wiilight.h>
#include <asndlib.h>
#include <mp3player.h>

// include generated header
#include "sample_mp3.h"

#include "gui.h"
#include "menu.h"
#include "restart.h"
#include "sys.h"
#include "video.h"
#include "wpad.h"
#include "fat.h"
#include "nand.h"
#include "globals.h"
#include "usbstorage.h"

// Globals
CONFIG gConfig;

// Prototypes
extern u32 WaitButtons (void);

void SetDefaultConfig (void);
int ReadConfigFile (char *configFilePath);
int GetIntParam (char *inputStr);
int GetStartupPath (char *startupPath, char *inputStr);
int GetStringParam (char *outParam, char *inputStr, int maxChars);



void Disclaimer(void)
{
MP3Player_PlayBuffer(sample_mp3, sample_mp3_size, NULL);
Con_BgColor(7, 1);
	Con_FgColor(0, 0);
	Con_Clear();
	switch (CONF_GetLanguage()) {
		case CONF_LANG_FRENCH:
	/* Print disclaimer */
	
	printf("\t                   \n\n");

	printf(" \t                    BIENVENUE SUR I/S WAD \n\n");
Con_FgColor(1, 2);
	printf(" Les erreures s'affichent en rouge\n");
Con_FgColor(2, 2);
	printf(" Les reussites s'affichent en vert \n");
Con_FgColor(0, 0); 
	printf(" \n");
  printf("\t \n");
	printf("\t>> Pressez A pour continuer\n");
	printf("\t>> Sinon HOME ou START pour redemarrer ;)  \n\n");
	printf(" \n\n");
	printf("\t                                               Merci Wii-Info.fr\n");
	break;
	default:case CONF_LANG_ENGLISH:
	/* Print disclaimer */
	
	printf("\t                   \n\n");

	printf(" \t                    WELCOME TO I/S WAD \n");
	Con_FgColor(1, 2);
	printf(" Les erreures s'affichent en rouge\n");
Con_FgColor(2, 2);
	printf(" Les reussite s'affichent en vert \n");
Con_FgColor(0, 0); 
	printf(" \n");
  printf("\t \n");
	printf("\t>> Press A to continue\n");
	printf("\t>> Otherwise HOME or START for restart ;)  \n\n");
	printf(" \n\n");
	printf("\t                                              Thanks Wii-Info.fr\n");
break;
}
	/* Wait for user answer */
	for (;;) {
		//u32 buttons = Wpad_WaitButtons();
		u32 buttons = WaitButtons();

		/* A button */
		if (buttons & WPAD_BUTTON_A)
			break;

		/* Home button */
		if (buttons & WPAD_BUTTON_HOME)
			Restart();
	}
}


  
	

int main(int argc, char **argv)
{


	
	/* Initialize subsystems */
	Sys_Init();

	/* Set video mode */
	Video_SetMode();

	/* Initialize console */
	Gui_InitConsole();

	/* Draw background */
	Gui_DrawBackground();

	/* Initialize Wiimote and GC Controller */
	Wpad_Init();
	PAD_Init ();
	WIILIGHT_Init();
        USBStorage_Init();

        /* Initialise the audio subsystem*/
	ASND_Init(NULL);
	MP3Player_Init();

	
        // Prevent IOS36 loading at startup
s32 __IOS_LoadStartupIOS()
{
	return 0;
}
	/* Print disclaimer */
	Disclaimer();
	
	// Set the defaults
	SetDefaultConfig ();

	// Read the config file
	ReadConfigFile (WM_CONFIG_FILE_PATH);

	/* Menu loop */
	Menu_Loop();

	/* Restart Wii */
	Restart_Wait();

	return 0;

}


int ReadConfigFile (char *configFilePath)
{
    int retval = 0;
	FILE *fptr;
	char *tmpStr = malloc (MAX_FILE_PATH_LEN);
	char tmpOutStr [40];
	int i;

	if (tmpStr == NULL)
		return (-1);

	fatDevice *fdev = &fdevList[0];
	s32 ret = Fat_Mount(fdev);
	
	if (ret < 0) 
	{
		printf(" ERREUR! (ret = %d)\n", ret);
		// goto err;
		retval = -1;
	}
	else
	{
		// Read the file
		fptr = fopen (configFilePath, "rb");
		if (fptr != NULL)
		{	
			// Read the options
			char done = 0;

			while (!done)
			{
				if (fgets (tmpStr, MAX_FILE_PATH_LEN, fptr) == NULL)
					done = 1;
				else if (isalpha(tmpStr[0]))
				{
					
				
					// Get startup path
					if (strncmp (tmpStr, "StartupPath", 11) == 0)
					{
						// Get startup Path
						GetStartupPath (gConfig.startupPath, tmpStr);
					}
					
					
						
					
				}
			} // EndWhile
			
			// Close the config file
			fclose (fptr);
		}
		else
		{
			// If the wm_config.txt file is not found, just take the default config params
			//printf ("Config file is not found\n");  // This is for testing only
			//WaitButtons();
		}
		Fat_Unmount(fdev);
	}

	// Free memory
	free (tmpStr);

	return (retval);
} // ReadConfig


void SetDefaultConfig (void)
{
	
	// Default startup folder
	strcpy (gConfig.startupPath, WAD_ROOT_DIRECTORY);
	
	gConfig.cIOSVersion = CIOS_VERSION_INVALID;            // Means that user has to select later
	gConfig.fatDeviceIndex = FAT_DEVICE_INDEX_INVALID;     // Means that user has to select
	gConfig.nandDeviceIndex = NAND_DEVICE_INDEX_INVALID;   // Means that user has to select

} // SetDefaultConfig


int GetStartupPath (char *startupPath, char *inputStr)
{
	int i = 0;
	int len = strlen (inputStr);
	
	// Find the "="
	while ((inputStr [i] != '=') && (i < len))
	{
		i++;
	}
	i++;

	// Get to the "/"
	while ((inputStr [i] != '/') && (i < len))
	{
		i++;
	}

	// Get the startup Path
	int count = 0;
	while (isascii(inputStr [i]) && (i < len) && (inputStr [i] != '\n') && 
	         (inputStr [i] != '\r') && (inputStr [i] != ' '))
	{
		startupPath [count++] = inputStr [i++];
	}
	startupPath [count] = 0; // NULL terminate

	return (0);
} // GetStartupPath

int GetIntParam (char *inputStr)
{
	int retval = 0;
	int i = 0;
	int len = strlen (inputStr);
	char outParam [40];
	
	// Find the "="
	while ((inputStr [i] != '=') && (i < len))
	{
		i++;
	}
	i++;
	
	// Get to the first alpha numeric character
	while ((isdigit(inputStr [i]) == 0) && (i < len))
	{
		i++;
	}

	// Get the string param
	int outCount = 0;
	while ((isdigit(inputStr [i])) && (i < len) && (outCount < 40))
	{
		outParam [outCount++] = inputStr [i++];
	}
	outParam [outCount] = 0; // NULL terminate
	retval = atoi (outParam);
	
	return (retval);
} // GetIntParam


int GetStringParam (char *outParam, char *inputStr, int maxChars)
{
	int i = 0;
	int len = strlen (inputStr);
	
	// Find the "="
	while ((inputStr [i] != '=') && (i < len))
	{
		i++;
	}
	i++;
	
	// Get to the first alpha character
	while ((isalpha(inputStr [i]) == 0) && (i < len))
	{
		i++;
	}
	
	// Get the string param
	int outCount = 0;
	while ((isalnum(inputStr [i])) && (i < len) && (outCount < maxChars))
	{
		outParam [outCount++] = inputStr [i++];
	}
	outParam [outCount] = 0; // NULL terminate
	
	return (0);
}
